package com.example.tool.db;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;

public class SqlConnection {
  private static final Logger LOGGER = LoggerFactory.getLogger(SqlConnection.class);
  private static final String ORACLE_DRIVER_NAME = "oracle.jdbc.driver.OracleDriver";
  private static final String MYSQL_DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
  private static final String SQLSERVER_DRIVER_NAME = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

  private SqlConnection() {
  }

  private static final class ConnectionHolder {
    static final SqlConnection connection = new SqlConnection();
  }

  public static synchronized SqlConnection getInstance() {
    return ConnectionHolder.connection;
  }

  public Connection getConnection(String sqlType, String url, String user, String password) throws Exception {
    try {
      switch (sqlType) {
        case "SQLSERVER" -> Class.forName(SQLSERVER_DRIVER_NAME);
        case "MYSQL" -> Class.forName(MYSQL_DRIVER_NAME);
        case "ORACLE" -> Class.forName(ORACLE_DRIVER_NAME);
        default -> throw new Exception("暂不支持该类数据库连接");
      }
      return DriverManager.getConnection(url, user, password);
    } catch (Exception e) {
      LOGGER.info("数据库连接出错：{}", e.getMessage(), e);
      throw new Exception("数据库连接出错：" + e.getMessage(), e);
    }
  }
}
